<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { loginAPI } from '@/apis/user'
import { useUserStore } from '@/stores/user'
import type { LoginParams } from '@/types/user'
import { useRouter } from 'vue-router'

// interface FormData {
//   username: string
//   password: string
// }

const formData = ref<LoginParams>({
  mobile: '18366368132',
  code: '246810',
})

const fromrules = ref<FormRules<LoginParams>>({
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3456789]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码格式不正确', trigger: 'blur' },
  ],
})

const refRorm = ref<FormInstance>()
const store = useUserStore()
const router = useRouter()

const onclick = () => {
  refRorm.value?.validate(async (res) => {
    console.log(res)
    if (res) {
      const res = await loginAPI(formData.value)
      console.log(res)
      store.setToken(res.data.token)
      router.push('/')
      ElMessage.success('登录成功')
    }
  })
}
</script>

<template>
  <div class="container">
    <el-card shadow="always">
      <img src="../../assets/images/logo.png" alt="" class="logo" />
      <el-form :model="formData" :rules="fromrules" ref="refRorm">
        <el-form-item prop="mobile">
          <el-input
            placeholder="请输入手机号"
            style="height: 40px"
            v-model="formData.mobile"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item prop="code">
          <el-input
            placeholder="请输入验证码"
            style="height: 40px"
            v-model="formData.code"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-checkbox>我已阅读并同意[用户协议] 和 [隐私条款]</el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" style="height: 40px" @click="onclick()">登录</el-button>
        </el-form-item>
      </el-form>
      {{ formData }}
    </el-card>
  </div>
</template>

<style scoped>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: url('../../assets/images/login.png');
}
.logo {
  width: 420px;
}
.el-card {
  display: flex;
  justify-content: center;
  width: 500px;
  height: 400px;
}
.el-button {
  width: 100%;
}
</style>

<style>
* {
  margin: 0px;
  padding: 0px;
}
</style>
